package com.igoal.campaign.newyear2011.web;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.igoal.campaign.base.BaseCampainController;
import com.igoal.campaign.service.CampaignService;
import com.igoal.dto.GoalDTO;
import com.igoal.dto.UserDTO;
import com.igoal.service.GoalManager;
import com.igoal.service.UserGoalManager;
import com.igoal.utils.CalendarUtils;
import com.igoal.web.Constants;

@Controller
public class NewYear2011Controller extends BaseCampainController {
	private final int MAX_GOALS = 30;
	@Autowired
	GoalManager goalManager;
	
	@Autowired
	UserGoalManager userGoalManager;
	
	CampaignService campaignService;
	
	@RequestMapping(method=RequestMethod.GET, value="/cp/newyear2011.html")
	public String loadPage(ModelMap modelMap){		
//		CampaignDTO campaignDTO = campaignService.getCampaignByName("newyear2011");
//		if(campaignDTO == null){
//			return REDIRECT_TO_HOMEPAGE;
//		}else{
//			if(!campaignService.isValidCampaign(campaignDTO)){
//				return REDIRECT_TO_HOMEPAGE;
//			}
//		}
		
		NewYear2011Model model = new NewYear2011Model();
		model.setSubscriptionType(Constants.USER_SUBSCRIPTION_MONTHLY);		
		
		Date newyear = CalendarUtils.getStartDate(CalendarUtils.parseDate("1/1/2010", CalendarUtils.DD_MM_YYYY));
		model.setGoalCount(goalManager.countGoalsFrom(newyear));
		model.setGoals(goalManager.getRandomGoals(MAX_GOALS));
		
		if(isLoginUser()){
			model.setUserInSession(getUserInSession());			
		}
		
		applyModel(modelMap, model);
		
		return getViewPrefix() + "newyear";
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/cp/newyear2011.html")
	public String submitGoal(@ModelAttribute("data") NewYear2011Model model){
		if(model.getSubscriptionType() != Constants.USER_SUBSCRIPTION_WEEKLY &&
				model.getSubscriptionType() != Constants.USER_SUBSCRIPTION_MONTHLY &&
				model.getSubscriptionType() != Constants.USER_SUBSCRIPTION_EVERY_THREE_MONTHS &&
				model.getSubscriptionType() != Constants.USER_SUBSCRIPTION_EVERY_SIX_MONTHS){
			model.setSubscriptionType(Constants.USER_SUBSCRIPTION_MONTHLY);
		}
		
		String username = getUserInSession();
		UserDTO userDTO = getUserManagerExt().saveSubcriptionType(username, model.getSubscriptionType(), true);
		GoalDTO goalDTO = new GoalDTO();
		goalDTO.setTitle(model.getGoal());
		userGoalManager.createNewGoal(goalDTO, userDTO);
		
		return "redirect:/dashboard.html";
	}

	@Override
	public String getViewPrefix() {
		return "newyear2011/";
	}
}
